<?php
require('init.php');
$title = 'INscripcion';
require(LIBWWWDIR . '/header.php');


function checkUsername($user){
	$conexion = connect();
	$query = "SELECT username FROM users WHERE username = '".$user ."'";
	$res = mysql_query($query, $conexion) or die(mysql_error());
	$exit_user = mysql_fetch_array($res, MYSQL_NUM);
	$tam_res = mysql_num_rows($res);
	if( $tam_res == 1 )
		return true; // user existente
	else
		return false; // user no existente
}
//verificar si ya existe la inscripcion
function checkSolicitud($conexion, $user, $cid, $tab){
	$ver = "SELECT date FROM ".$tab." WHERE username = '".$user ."' AND cid = '".$cid."'";
	$res = mysql_query($ver, $conexion) or die(mysql_error());
	$exit_user = mysql_fetch_array($res, MYSQL_NUM);
	$tam_res = mysql_num_rows($res);
	if( $tam_res == 1 )
		return true; // inscripcion existente
	else
		return false; // inscripcion no existente
	
}

if( !(isset($_GET['c'])) ){
	header( 'Location:index.php' );
}
$cid = $_GET['c'];
$res = $DB->q('TABLE SELECT * FROM contest WHERE cid = %i',$cid);
$category = $res[0]['categoryid'];
$interno = $userdata[18];
$user = $userdata[0];
$members = $userdata[15]." ".$userdata[2]." ".$userdata[3];

if( ! checkUsername($user) ){
	echo '<script type="text/javascript" >'.
			'alert("Usuario no valido, Debe estar registrado");'.
		'</script>';
	exit;
}
$conexion = connect();

		//*** user interno ////*** user externo
// Inner Training(2); National Training(4)
if( $category == '1' OR $category == '2' OR $category == '4' ){
	if( $category == '1' )
		$table = "ins_in_contest";
	if( $category == '2' )
		$table = "ins_in_training";
	if( $category == '4' )
		$table = "ins_nat_training";
	//verificar que el usuario que se esté inscribiendo, este registrado como usuario
	//verificar que no exista la solicitud
	//if( ! checkSolicitud($conexion, $user, $cid, $table) ){
		$hora = now();
		$query = "INSERT INTO ".$table." (username, cid, date) 
			values('$user', '$cid', '$hora')";
		$res = mysql_query($query, $conexion) or die(mysql_error());
		if($res){
				$all_ok = "1";
				//echo "Se ha guardado con exito!!!!!!!!!!!<br>";
			}else{
				$all_ok  = "0" ;
				//echo "chanflee!! :S <br>";
			}
			if( $all_ok == "1" ){
				echo '<script type="text/javascript" >'.
			'alert("Inscripción exitosa. Login y password del team = a datos usuario ");'.
			'</script>';
			}else{
				echo '<script type="text/javascript" >'.
				'alert("Error en la inscripcción ");'.
				'</script>';
			}
	/*}else{
			echo '<script type="text/javascript" >'.
			'alert("Ya está inscrito ");'.
			'</script>';
	}*/
}else{
	echo '<script type="text/javascript" >'.
			'alert("opcion desconocida ");'.
			'</script>'; 
}

//header( 'Location:next_contest.php' );
